//
//  PhotoLibraryViewController.swift
//  MT
//
//  Created by M on 2019/12/22.
//  Copyright © 2019 张强. All rights reserved.
//

import UIKit
import MTCategory
import YPNavigationBarTransition

@objc
protocol PhotoLibraryViewControllerDelegate: NSObjectProtocol {
    
    /// 选中图片 / 视频 - 只有 maxSelectdCount == 1 时调用 或 选中视频时调用
    @objc optional func photoLibraryController(_ controller: PhotoLibraryViewController, didSelectAssetWith asset: MTAsset)
    /// 选中图片 - 数组返回 maxSelectdCount > 1 时调用
    @objc optional func photoLibraryController(_ controller: PhotoLibraryViewController, didSelectAssetsWith assets: [MTAsset])
    
}

class PhotoLibraryViewController: BaseViewController {
    
    /// 代理
    weak var delegate: PhotoLibraryViewControllerDelegate?
    /// 确认按钮
    var confirmButton: UIBarButtonItem?
    
    /// 相册模型
    var assets: [MTAsset]?
    /// 是否只展示视频
    var isOnlyVideo: Bool = false
    /// 已选相册模型
    var selectedAssets: [MTAsset] = [] {
        didSet {
            confirmButton?.isEnabled = selectedAssets.count > 0
        }
    }
    /// 是否选择到最大数量 - 是否不能再选
    private var photoLibrarySelectable: Bool {
        return selectedAssets.count == maxSelectdCount || (selectedAssets.first?.mediaType == .video)
    }
    /// 所有视频是否可选
    private var isAllVideoEnabled: Bool = true
    /// 视频是否可选
    var allowVideoSelection: Bool = true
    /// 是否可多选
    var isMultipleSlectEnabled: Bool = false
    /// 最多可选择几张
    var maxSelectdCount: Int = 9
    
    lazy var collectionView: UICollectionView = {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: ScreenWidth / 3, height: ScreenWidth / 3)
        flowLayout.minimumLineSpacing = 0
        flowLayout.minimumInteritemSpacing = 0
        let cv = UICollectionView(frame: self.view.bounds, collectionViewLayout: flowLayout)
        cv.backgroundColor = UIColor.theme.background
        cv.showsVerticalScrollIndicator = false
        cv.delegate = self
        cv.dataSource = self
        /// 注册 cell
        cv.register(PhotoLibarayCollectionViewCell.self, forCellWithReuseIdentifier: String(describing: PhotoLibarayCollectionViewCell.self))
        cv.register(PhotoLibrarySelectableCollectionViewCell.self, forCellWithReuseIdentifier: String(describing: PhotoLibrarySelectableCollectionViewCell.self))
        return cv
    }()
    
}

// MARK: ------------------ Overrides ----------------------
extension PhotoLibraryViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
        isOnlyVideo ? fetchVideos() : fetchAssets()
        initializeUI()
    }
    
}

// MARK: ------------------ 初始化 ----------------------
extension PhotoLibraryViewController {
    
    private func setup() {
        let button = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
        button.setImage(UIImage(named: "icon_dismiss"), for: .normal)
        button.adjustsImageWhenHighlighted = false
        button.addTarget(self, action: #selector(photoLibrary(didClickDismissButton:)), for: .touchUpInside)
        let leftButton = UIBarButtonItem(customView: button)
        self.navigationItem.leftBarButtonItem = leftButton
        
        let r_btn = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 30))
        r_btn.setBackgroundImage(UIImage(color: UIColor(hex: 0x5d5d5d)), for: .disabled)
        r_btn.setBackgroundImage(UIImage(color: UIColor.theme.main), for: .normal)
        r_btn.setTitle("确定", for: .normal)
        r_btn.setTitleColor(.black, for: .normal)
        r_btn.titleLabel?.font = PingFangSCSemiboldFont(14)
        r_btn.adjustsImageWhenHighlighted = false
        r_btn.layer.cornerRadius = 3
        r_btn.clipsToBounds = true
        r_btn.addTarget(self, action: #selector(photoLibrary(didClickConfirmButton:)), for: .touchUpInside)
        let rightButton = UIBarButtonItem(customView: r_btn)
        rightButton.isEnabled = false
        self.confirmButton = rightButton
        self.navigationItem.rightBarButtonItem = rightButton
    }
    
    private func fetchAssets() {
        MTAssetLibrary.request { [weak self] (flag) in
            guard let weakself = self else { return }
            DispatchQueue.main.async {
                if flag {
                    let option = MTAssetLibraryOption()
                    option.isVideoPickingAllowed = weakself.allowVideoSelection
                    option.isNetworkAccessEnable = true
                    MTAssetLibrary(option: option).requestForCameraRollAlbum { [weak self] (cameraRollAlbum) in
                        guard let weakSelf = self else { return }
                        weakSelf.assets = cameraRollAlbum.assets
                        weakSelf.collectionView.reloadData()
                    }
                } else {
                    AlertManager.presentAlertView(message: "请开启相册权限")
                }
            }
        }
    }
    
    private func fetchVideos() {
        MTAssetLibrary.request { [weak self] (flag) in
            guard let weakself = self else { return }
            DispatchQueue.main.async {
                if flag {
                    let option = MTAssetLibraryOption()
                    option.isVideoPickingAllowed = weakself.allowVideoSelection
                    option.isNetworkAccessEnable = true
                    MTAssetLibrary(option: option).requestForVideoAlbum { [weak self] (cameraRollAlbum) in
                        guard let weakSelf = self else { return }
                        weakSelf.assets = cameraRollAlbum.assets
                        weakSelf.collectionView.reloadData()
                    }
                } else {
                    AlertManager.presentAlertView(message: "请开启相册权限")
                }
            }
        }
    }
    
    private func initializeUI() {
        view.addSubview(collectionView)
    }
    
}

// MARK: ------------------ 事件方法 ----------------------
@objc
extension PhotoLibraryViewController {

    /// 点击关闭按钮
    private func photoLibrary(didClickDismissButton sender: UIBarButtonItem) {
        dismiss(animated: true, completion: nil)
    }
    
    /// 点击确定按钮
    private func photoLibrary(didClickConfirmButton sender: UIBarButtonItem) {
        if let delegate = delegate {
            delegate.photoLibraryController?(self, didSelectAssetsWith: selectedAssets)
        }
        self.dismiss(animated: true, completion: nil)
    }
    
}

// MARK: ------------------------------------ 资源选择相关 ----------------------------------------
extension PhotoLibraryViewController {
    
    /// 选中资源
    private func select(_ asset: MTAsset) {
        asset.isSelected = true
        /// 选中逻辑
        if !selectedAssets.contains(asset) {
            selectedAssets.append(asset)
        }
        if photoLibrarySelectable {
            disableAllUnselectedAssets()
        } else if selectedAssets.first?.mediaType != .video {
            setAllVideoEnabled(false)
        }
        confirmButton?.isEnabled = selectedAssets.count != 0
    }
    
    /// 取消选中资源
    private func deselect(_ asset: MTAsset) {
        asset.isSelected = false
        /// 未选中逻辑
        if selectedAssets.contains(asset), let idx = selectedAssets.firstIndex(of: asset) {
            selectedAssets.remove(at: idx)
        }
        if selectedAssets.count == 0 {
            reenableAllUnselectedAssets()
        }
        confirmButton?.isEnabled = selectedAssets.count != 0
    }

    /// 设置是否禁止所有视频选择
    private func setAllVideoEnabled(_ isEnabled: Bool) {
        if isAllVideoEnabled == isEnabled { return }
        guard let assets = assets else { return }
        for asset in assets {
            if asset.mediaType == .video {
                asset.isEnabled = isEnabled
            }
        }
        isAllVideoEnabled = isEnabled
    }
    
    /// 禁止所有未选中的资源选择
    private func disableAllUnselectedAssets() {
        guard let assets = assets else { return }
        for asset in assets {
            asset.isEnabled = selectedAssets.contains(asset)
        }
        isAllVideoEnabled = false
    }
    
    /// 恢复所有未选中的资源选择
    private func reenableAllUnselectedAssets() {
        guard let assets = assets else { return }
        for asset in assets {
            asset.isEnabled = true
        }
        isAllVideoEnabled = true
    }
    
}

// MARK: ------------------ 所有代理 ----------------------
// MARK: ------------------ UICollectionViewDelegate ----------------------
extension PhotoLibraryViewController: UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let assets = assets else { return }
        let asset = assets[indexPath.item]
        
        if maxSelectdCount == 1 || asset.mediaType == .video {
            if let delegate = delegate {
                delegate.photoLibraryController?(self, didSelectAssetWith: asset)
            }
            self.dismiss(animated: true, completion: nil)
        } else {
            (!asset.isSelected && !photoLibrarySelectable && asset.isEnabled) ? select(asset) : deselect(asset)
            collectionView.reloadData()
        }
    }
    
}

// MARK: ------------------ UICollectionViewDataSource ----------------------
extension PhotoLibraryViewController: UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        assets?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: PhotoLibrarySelectableCollectionViewCell.self), for: indexPath) as? PhotoLibrarySelectableCollectionViewCell else {
            return collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: PhotoLibrarySelectableCollectionViewCell.self), for: indexPath)
        }
        cell.isSelectButtonHidden = maxSelectdCount == 1
        cell.asset = self.assets?[indexPath.item]
        return cell
    }
    
}
